package com.longqin.wechat.controller;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.longqin.wechat.entity.BaseResponse;
import com.longqin.wechat.entity.MyException;
import com.longqin.wechat.util.ResponseEnum;

/**自定义全局异常捕获
 * @author longqin
 *
 */
@RestControllerAdvice
public class ExceptionController {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	/**自定义异常
	 * @param ex
	 * @return
	 */
	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(MyException.class)
	public BaseResponse onMyException(MyException ex) {
		logger.error("自定义异常:"+ex.getMessage());
		return ex.getError();
	}
	
	/**
	 * @Description: 参数验证异常(参数校验抛出的异常)
	 * @param ex
	 * @return
	 * @Author longqin
	 * @Date 2025-05-07
	 * 
	 */
	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(BindException.class)
	public BaseResponse onBindException(BindException ex) {
		String msg=ex.getBindingResult().getFieldErrors().get(0).getDefaultMessage();
		logger.error("参数验证异常:"+msg);
		return new BaseResponse(ResponseEnum.BADPARAM.getCode(),msg);
	}
	
	/**
	 * @Description: 参数验证异常
	 * @param ex
	 * @return
	 * @Author longqin
	 * @Date 2025-05-07
	 * 
	 */
	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(MissingServletRequestParameterException.class)
	public BaseResponse onBindException(MissingServletRequestParameterException ex) {
		logger.error("参数验证异常:"+ex.getMessage());
		ex.printStackTrace();
		return new BaseResponse(ResponseEnum.BADPARAM.getCode(), ex.getMessage());
	}
	

	/**
	 * @Description: 请求方式错误(post或者get)
	 * @param request
	 * @param ex
	 * @return
	 * @Author longqin
	 * @Date 2025-05-07
	 * 
	 */
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	@ResponseStatus(HttpStatus.OK)
	public BaseResponse onHttpRequestMethodNotSupportedException(HttpServletRequest request, Throwable ex) {
		logger.error("捕获异常:"+ex.getMessage());
		return new BaseResponse(ResponseEnum.ERROR.getCode(), ex.getMessage());
	}
	
	/**
	 * @Description: 捕捉其他所有异常
	 * @param request
	 * @param ex
	 * @return
	 * @Author longqin
	 * @Date 2025-05-07
	 * 
	 */
	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public BaseResponse globalException(HttpServletRequest request, Throwable ex) {
		logger.error("捕获异常:"+ex.getMessage(),ex);
		//ex.printStackTrace();
		return new BaseResponse(ResponseEnum.ERROR.getCode(), "请求异常");
	}

}

